package net.pzc.filechooser;

import java.awt.Cursor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import net.pzc.log.ILiteLogger;
import net.pzc.log.LoggerFactory;
import sun.awt.shell.ShellFolder;

public class OpenFileAction extends Thread {

	public static ILiteLogger logger = LoggerFactory.getLogger(OpenFileAction.class);

	private JComponent ui = null;
	private boolean init = false;
	private File aimFile = null;
	private boolean openDirFlg = false;
	private FastFileChooser chooser = null;
	private boolean pcFlg = false;

	private List<String> pathList = new ArrayList<String>();

	private boolean linkNotExist = false;

	public OpenFileAction(JComponent ui, boolean init, String[] pathArray, FastFileChooser chooser, boolean pcFlg) {
		this.ui = ui;
		this.init = init;
		for (String path : pathArray) {
			this.pathList.add(path);
		}
		this.chooser = chooser;
		this.pcFlg = pcFlg;
		chooser.getCmb().setEnabled(false);
		chooser.getBtn_up().setEnabled(false);
		ui.setEnabled(false);
		chooser.getCmb_fileType().setEnabled(false);
		chooser.getBtn_open().setEnabled(false);
		ui.getParent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	}

	public OpenFileAction(JComponent ui, boolean init, String path, FastFileChooser chooser, boolean pcFlg) {
		this(ui, init, new String[] { path }, chooser, pcFlg);
	}

	@Override
	public void run() {
		boolean firstTime = true;
		while (this.pathList.size() > 0) {
			String path = this.pathList.remove(0);
			if (firstTime == true || linkNotExist == true) {
				// 第一次必须做
				// 找不到文件/文件夹也要继续做
				firstTime = false;
				linkNotExist = false;
				this.aimFile = new File(path);
				this.execute();
			}

			if (linkNotExist == false) {
				this.pathList.clear();
			}
		}
	}

	private void execute() {
		logger.debug("--- execute start ---");
		Thread t = new Thread() {
			@Override
			public void run() {
				logger.debug("--- check folder start ---");
				logger.debug("aimFile: " + aimFile.getAbsolutePath());
				if (aimFile.isFile()) {
					logger.debug("it is File");
					try {
						ShellFolder sf = ShellFolder.getShellFolder(aimFile);
						if (sf.isLink()) {
							logger.debug("it is Link(Shortcut)");
							ShellFolder linkLocation = sf.getLinkLocation();
							logger.debug(linkLocation);
							if (linkLocation == null) {
								throw new FileNotFoundException();
							}
							if (linkLocation.exists()) {
								logger.debug("link exists");
								if (linkLocation.isDirectory()) {
									logger.debug("link is Directory");
									openDirFlg = true;
									aimFile = new File(linkLocation.getAbsolutePath());
								} else if (linkLocation.isFile()) {
									logger.debug("link is File");
									aimFile = linkLocation.getAbsoluteFile();
								}
							} else {
								linkNotExist = true;
								logger.debug("link not exists");
							}
						}
					} catch (FileNotFoundException e) {
						logger.debug("FileNotFoundException: " + e);
						linkNotExist = true;
						e.printStackTrace();
					}
				} else if (aimFile.isDirectory()) {
					logger.debug("it is Folder");
					openDirFlg = true;
				} else {
					logger.debug("it is UNKNOWN");
					linkNotExist = true;
				}

				if (init == true && linkNotExist == false && aimFile.isFile()) {
					// 画面初めて表示されるとき
					aimFile = aimFile.getParentFile();
					openDirFlg = true;
				}

				logger.debug("openDirFlg: " + openDirFlg);
				logger.debug("--- check folder end ---");
			}
		};
		t.start();

		try {
			t.join(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		// System.out.println(t.isAlive());
		if (t.isAlive()) {
			logger.debug("--- execute end ---");
			t.interrupt();
			linkNotExist = true;
		}
		// System.out.println(t.isInterrupted());

		try {
			finishWork();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("--- execute end ---");
	}

	private void finishWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				logger.debug("--- finishWork.run start ---");
				if (pathList.size() == 0) {
					ui.getParent().setCursor(Cursor.getDefaultCursor());
					chooser.getCmb().setEnabled(true);
					chooser.getBtn_up().setEnabled(true);
					chooser.getBtn_open().setEnabled(true);
					ui.setEnabled(true);
					chooser.getCmb_fileType().setEnabled(true);
				}

				logger.debug("◆◇◆◇◆linkNotExist◆◇◆◇◆: " + linkNotExist);
				if (linkNotExist == false) {
					chooser.updateStatus("");
					logger.debug("aimFile: " + aimFile.getAbsolutePath());
					// 只有打开成功之后，才能更新当前Path
					chooser.setSelectedAbsolutePath(aimFile.getAbsolutePath());
					if (openDirFlg) {
						if (pcFlg) {
							logger.debug("MergeCmbAction");
							MergeCmbAction a = new MergeCmbAction(chooser.getCmb(), aimFile.getAbsolutePath(), chooser);
							a.start();
						} else {
							chooser.rescanCurrentDirectory();
						}
					} else {
						chooser.setReturnValue(JOptionPane.OK_OPTION);
						chooser.closeDialog();
					}
				} else {
					chooser.updateStatus("◆◇◆◇◆linkNotExist◆◇◆◇◆");
				}
				logger.debug("--- finishWork.run end ---");
			}

		});
	}

}
